﻿using Dapper.Contrib.Extensions;
using Dapper;
using IntelligentGateway.Model.Panel;

namespace IntelligentGateway.Data
{
    public class PanelDeviceInfoDA
    {
        public bool UpdateAllDevState()
        {
            using (var conn = DataFactory.GetMYSQLConnection())
            {
                try
                {
                    int _ = conn.Execute("Update paneldeviceinfo set StateID=@StateID", new { StateID = 2 });
                    return _ > 0;
                }
                catch (Exception e)
                {
                    return false;
                }
            }
        }
        public bool UpdateDevState(PanelDeviceInfo c)
        {
            using (var conn = DataFactory.GetMYSQLConnection())
            {
                try
                {
                    int _ = conn.Execute("Update PanelDeviceInfo set StateID=@StateID,LastStatusTime=@LastStatusTime where NO=@NO", new { StateID = c.StateID, LastStatusTime = c.LastStatusTime, NO = c.NO });
                    return _ > 0;
                }
                catch (Exception e)
                {
                    return false;
                }
            }
        }
        public bool InsertDeviceInfo(PanelDeviceInfo c)
        {
            using (var conn = DataFactory.GetMYSQLConnection())
            {
                try
                {
                    long _ = conn.Insert<PanelDeviceInfo>(c);
                    return _ > 0;
                }
                catch (Exception e)
                {
                    return false;
                }
            }
        }
        public bool CheckDevExist(string NO)
        {
            using (var conn = DataFactory.GetMYSQLConnection())
            {
                try
                {
                    int _ = conn.ExecuteScalar<int>("select count(ID) from PanelDeviceInfo where NO=@NO", new { NO = NO });
                    return _ > 0;
                }
                catch (Exception e)
                {
                    return false;
                }
            }
        }
        public string GetDeviceIDFromPanel(string PanelIP)
        {
            using (var conn = DataFactory.GetMYSQLConnection())
            {
                try
                {
                    string DeviceID = conn.ExecuteScalar<string>("SELECT NO FROM PanelDeviceInfo where Indent=@PanelIP",new { PanelIP = PanelIP });
                    return DeviceID;
                }
                catch (Exception e)
                {
                    return null;
                }
            }
        }
    }
}
